#include "TestTextEdit.h"
#include<QVBoxLayout>
#include<QTextEdit>
#include<QPushButton>
#include<QDebug>
#include<QToolBar>
#include<QFontComboBox>
#include<QSpinBox>
#include<QTextCursor>
#include<QColorDialog>
#include<QTimer>
#include<QTime>
#include<QScrollBar>

TestTextEdit::TestTextEdit(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *widget_central =new QWidget(this);
    setCentralWidget(widget_central);

    QVBoxLayout *layout = new QVBoxLayout(widget_central);

    // 创建 QTextEdit
    QTextEdit *textEdit = new QTextEdit();
    layout->addWidget(textEdit);

    // 示例1：设置初始文本 (纯文本或富文本)
    textEdit->setPlainText("这是一个纯文本示例。");
    // 或者
    textEdit->setHtml("<b>粗体</b>, <i>斜体</i>, <u>下划线</u><br>"
                      "<font color='red'>红色文字</font><br>"
                      "<a href='https://www.qt.io'>Qt 官网链接</a>");

    // 示例2：创建按钮演示操作
    QPushButton *btnGetText = new QPushButton("获取纯文本");
    QPushButton *btnGetHtml = new QPushButton("获取HTML");
    QPushButton *btnClear = new QPushButton("清空");
    QPushButton *btnAppend = new QPushButton("追加文本");
    QPushButton *btnToggleReadOnly = new QPushButton("切换只读");

    layout->addWidget(btnGetText);
    layout->addWidget(btnGetHtml);
    layout->addWidget(btnClear);
    layout->addWidget(btnAppend);
    layout->addWidget(btnToggleReadOnly);

    // 连接按钮信号到槽函数
    QObject::connect(btnGetText, &QPushButton::clicked, [textEdit]() {
        qDebug() << "纯文本内容:\n" << textEdit->toPlainText();
    });
    QObject::connect(btnGetHtml, &QPushButton::clicked, [textEdit]() {
        qDebug() << "HTML 内容:\n" << textEdit->toHtml();
    });
    QObject::connect(btnClear, &QPushButton::clicked, textEdit, &QTextEdit::clear);
    QObject::connect(btnAppend, &QPushButton::clicked, [textEdit]() {
        textEdit->append("-- 这是追加的文本 --");
    });
    QObject::connect(btnToggleReadOnly, &QPushButton::clicked, [textEdit]() {
        textEdit->setReadOnly(!textEdit->isReadOnly());
        qDebug() << "只读状态:" << textEdit->isReadOnly();
    });

    // 示例3：响应文本变化信号
    QObject::connect(textEdit, &QTextEdit::textChanged, []() {
        qDebug() << "文本内容发生了改变！";
    });

    //2 简易富文本编辑器（带格式工具栏）
    // 创建核心组件
    textEdit_2 = new QTextEdit(this);
    layout->addWidget(textEdit_2);
    // 创建工具栏
    formatBar = new QToolBar("格式工具栏", this);
    this->addToolBar(Qt::TopToolBarArea, formatBar);

    // 文本格式动作
    QAction *boldAction = new QAction(QIcon(":/images/bold.png"), "粗体", this);
    QAction *italicAction = new QAction(QIcon(":/images/italic.png"), "斜体", this);
    QAction *underlineAction = new QAction(QIcon(":/images/underline.png"), "下划线", this);

    // 字体控件
    QFontComboBox *fontCombo = new QFontComboBox(this);
    QSpinBox *fontSize = new QSpinBox(this);
    fontSize->setRange(6, 72);
    fontSize->setValue(12);

    // 颜色选择
    QAction *colorAction = new QAction(QIcon(":/color.png"), "文本颜色", this);

    // 添加到工具栏
    formatBar->addAction(boldAction);
    formatBar->addAction(italicAction);
    formatBar->addAction(underlineAction);
    formatBar->addWidget(fontCombo);
    formatBar->addWidget(fontSize);
    formatBar->addAction(colorAction);

    // 连接信号槽
    connect(boldAction, &QAction::triggered, this, &TestTextEdit::setBold);
    connect(italicAction, &QAction::triggered, this, &TestTextEdit::setItalic);
    connect(underlineAction, &QAction::triggered, this, &TestTextEdit::setUnderline);
    connect(fontCombo, &QFontComboBox::currentFontChanged, this, &TestTextEdit::setTextFont);
    connect(fontSize, QOverload<int>::of(&QSpinBox::valueChanged), this, &TestTextEdit::setFontSize);
    connect(colorAction, &QAction::triggered, this, &TestTextEdit::setTextColor);

    // 初始内容
    textEdit_2->setHtml("<h1>富文本编辑器</h1><p>尝试使用工具栏修改格式</p>");

    //3 彩色日志显示器
    logEdit = new QTextEdit(this);
    logEdit->setReadOnly(true);

    QPushButton *clearBtn = new QPushButton("清空日志", this);
    QPushButton *addLogBtn = new QPushButton("添加测试日志", this);

    layout->addWidget(logEdit);
    layout->addWidget(clearBtn);
    layout->addWidget(addLogBtn);

    // 连接信号
    connect(clearBtn, &QPushButton::clicked, logEdit, &QTextEdit::clear);
    connect(addLogBtn, &QPushButton::clicked, this, &TestTextEdit::addTestLog);

    // 模拟实时日志
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this]{
        addLog("定时日志: " + QTime::currentTime().toString(), Qt::darkGreen);
    });
    timer->start(2000);
}

void TestTextEdit::mergeFormat(const QTextCharFormat &format)
{
    QTextCursor cursor = textEdit_2->textCursor();
    if (!cursor.hasSelection())
        cursor.select(QTextCursor::WordUnderCursor);
    cursor.mergeCharFormat(format);
    textEdit_2->mergeCurrentCharFormat(format);
}

void TestTextEdit::setBold()
{
    QTextCharFormat fmt;
    fmt.setFontWeight(QFont::Bold);
    mergeFormat(fmt);
}

void TestTextEdit::setItalic()
{
    QTextCharFormat fmt;
    fmt.setFontItalic(true);
    mergeFormat(fmt);
}

void TestTextEdit::setUnderline()
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(true);
    mergeFormat(fmt);
}

void TestTextEdit::setTextFont(const QFont &f)
{
    QTextCharFormat fmt;
    fmt.setFontFamily(f.family());
    mergeFormat(fmt);
}

void TestTextEdit::setFontSize(int size)
{
    QTextCharFormat fmt;
    fmt.setFontPointSize(size);
    mergeFormat(fmt);
}

void TestTextEdit::setTextColor()
{
    QColor color = QColorDialog::getColor(textEdit_2->textColor(), this);
    if (!color.isValid()) return;

    QTextCharFormat fmt;
    fmt.setForeground(color);
    mergeFormat(fmt);
}

void TestTextEdit::addLog(const QString &message, const QColor &color)
{
    QString timestamp = QTime::currentTime().toString("[hh:mm:ss] ");

    logEdit->setTextColor(Qt::gray);
    logEdit->append(timestamp);

    logEdit->moveCursor(QTextCursor::End);
    logEdit->setTextColor(color);
    logEdit->insertPlainText(message);

    // 自动滚动到底部
    QScrollBar *sb = logEdit->verticalScrollBar();
    sb->setValue(sb->maximum());
}

void TestTextEdit::addTestLog()
{
    static int counter = 0;
    switch(counter++ % 4) {
    case 0: addLog("信息: 操作成功完成", Qt::blue); break;
    case 1: addLog("警告: 磁盘空间不足", QColor(255, 165, 0)); // 橙色
    case 2: addLog("错误: 文件打开失败!", Qt::red); break;
    case 3: addLog("调试: 变量值=42", Qt::darkCyan); break;
    }
}
